#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6

import torch
from torch import nn
import torch.nn.functional as F
from torchvision import models
# seed = 255
import math

# # cpu
# torch.manual_seed(seed)
# # gpu
# torch.cuda.manual_seed_all(seed) 

class MLP(nn.Module):
    def __init__(self, dim_in, dim_hidden, dim_out):
        super(MLP, self).__init__()
        self.layer_input = nn.Linear(dim_in, 512)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout()
        self.layer_hidden1 = nn.Linear(512, 256)
        self.layer_hidden2 = nn.Linear(256, 256)
        self.layer_hidden3 = nn.Linear(256, 64)
        # self.layer_hidden4 = nn.Linear(128, 64)
        self.layer_out = nn.Linear(64, dim_out)
        self.softmax = nn.Softmax(dim=1)
        self.weight_keys = [['layer_input.weight', 'layer_input.bias'],
                            ['layer_hidden1.weight', 'layer_hidden1.bias'],
                            ['layer_hidden2.weight', 'layer_hidden2.bias'],
                            ['layer_hidden3.weight', 'layer_hidden3.bias'],
                            # ['layer_hidden4.weight', 'layer_hidden4.bias'],
                            ['layer_out.weight', 'layer_out.bias']
                            ]

    def forward(self, x):
        x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])
        x = self.layer_input(x)
        x = self.relu(x)

        x = self.layer_hidden1(x)
        x = self.relu(x)

        x = self.layer_hidden2(x)
        x = self.relu(x)

        x = self.layer_hidden3(x)
        x = self.relu(x)

        # x = self.layer_hidden4(x)
        # x = self.relu(x)

        x = self.layer_out(x)
        return self.softmax(x)


class CNNMnist(nn.Module):
    def __init__(self, args):
        super(CNNMnist, self).__init__()
        # self.conv1 = nn.Conv2d(args.num_channels, 32, kernel_size=3)
        # self.conv2 = nn.Conv2d(32, 32, kernel_size=3)
        # self.conv2_drop = nn.Dropout2d()
        # self.fc1 = nn.Linear(800, 25)
        # self.fc2 = nn.Linear(25, args.num_classes)
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.pool2 = nn.MaxPool2d(2)
        self.fc1 = nn.Linear(256, 120)
        self.fc2 = nn.Linear(120, 25)
        self.fc3 = nn.Linear(25, 10)

    
        self.weight_keys = [
            ['fc1.weight', 'fc1.bias'],
            ['conv1.weight', 'conv1.bias'],
            ['conv2.weight', 'conv2.bias'],
            ['fc2.weight', 'fc2.bias'],
            ['fc3.weight', 'fc3.bias'],
            ]

    def forward(self, x):
        # x = F.relu(F.max_pool2d(self.conv1(x), 2))
        # x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        # x = x.view(-1, x.shape[1]*x.shape[2]*x.shape[3])
        # x = F.relu(self.fc1(x))
        # x = F.dropout(x, training=self.training)
        # x = self.fc2(x)
        # return F.log_softmax(x, dim=1)
        y = F.relu(self.conv1(x))
        y = self.pool1(y)
        y = F.relu(self.conv2(y))
        y = self.pool2(y)
        y = y.view(y.shape[0], -1)
        y = F.relu(self.fc1(y))
        y = F.relu(self.fc2(y))
        y = F.relu(self.fc3(y))
        return y

# class CNNMnist(nn.Module):
#     def __init__(self, args):
#         super(CNNMnist, self).__init__()
#         # todo 定义网络结构
#         self.hid_dim = 32

#         self.net = nn.Sequential(self.conv_block(1, self.hid_dim), self.conv_block(self.hid_dim, self.hid_dim),
#                                  self.conv_block(self.hid_dim, self.hid_dim), self.conv_block(self.hid_dim, 128))
#         self.logits = nn.Linear(128, args.num_classes)
#         self.weight_keys = [
            
            
#             ['net.0.0.weight','net.0.0.bias', 'net.0.1.weight','net.0.1.bias'],
#             ['net.3.0.weight','net.3.0.bias', 'net.3.1.weight','net.3.1.bias'],

#             ['net.1.0.weight','net.1.0.bias', 'net.1.1.weight','net.1.1.bias'],
#             ['net.2.0.weight','net.2.0.bias', 'net.2.1.weight','net.2.1.bias'],
#             ['logits.weight', 'logits.bias'],
#             ]
            
#     # todo 定义每个卷积层
#     def conv_block(self, in_channels, out_channels):
#         return nn.Sequential(
#             nn.Conv2d(in_channels, out_channels, 3, padding=1),
#             nn.BatchNorm2d(out_channels),
#             nn.ReLU(),
#             nn.MaxPool2d(2)
#         )

#     def forward(self, x):
#         x = self.net(x)
#         x = x.view(x.size(0), -1)
#         return self.logits(x)


class CNNCifar(nn.Module):
    def __init__(self, args):
        super(CNNCifar, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 100)
        self.fc3 = nn.Linear(100, args.num_classes)

     

        self.weight_keys = [['fc1.weight', 'fc1.bias'],
                            ['fc2.weight', 'fc2.bias'],
                            ['fc3.weight', 'fc3.bias'],
                            ['conv2.weight', 'conv2.bias'],
                            ['conv1.weight', 'conv1.bias'],
                            ]

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return F.log_softmax(x, dim=1)
        # return x



import torch.utils.model_zoo as model_zoo


from .group_normalization import GroupNorm2d

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
}


def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


def norm2d(planes, num_channels_per_group=32):
    # print("num_channels_per_group:{}".format(num_channels_per_group))
    if num_channels_per_group > 0:
        return GroupNorm2d(planes, num_channels_per_group, affine=True,
                           track_running_stats=False)
    else:
        return nn.BatchNorm2d(planes)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None,
                 group_norm=0):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm2d(planes, group_norm)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm2d(planes, group_norm)
        self.downsample = downsample
        self.stride = stride
        self.weight_keys = [['fc1.weight', 'fc1.bias'],
                    ['fc2.weight', 'fc2.bias'],
                    ['fc3.weight', 'fc3.bias'],
                    ['conv2.weight', 'conv2.bias'],
                    ['conv1.weight', 'conv1.bias'],
                    ]


    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None,
                 group_norm=0):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = norm2d(planes, group_norm)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = norm2d(planes, group_norm)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = norm2d(planes * 4, group_norm)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=10, group_norm=0):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm2d(64, group_norm)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0],
                                       group_norm=group_norm)
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       group_norm=group_norm)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       group_norm=group_norm)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       group_norm=group_norm)
        # self.avgpool = nn.AvgPool2d(7, stride=1)
        self.avgpool = nn.AvgPool2d(1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        self.weight_keys = [
            
            
            ['layer4.0.conv1.weight','layer4.0.bn1.weight', 'layer4.0.bn1.bias', 'layer4.0.conv2.weight','layer4.0.bn2.weight', 'layer4.0.bn2.bias'],
            ['layer4.1.conv1.weight','layer4.1.bn1.weight', 'layer4.1.bn1.bias', 'layer4.1.conv2.weight','layer4.1.bn2.weight', 'layer4.1.bn2.bias'],
            ['layer3.0.conv1.weight','layer3.0.bn1.weight', 'layer3.0.bn1.bias', 'layer3.0.conv2.weight','layer3.0.bn2.weight', 'layer3.0.bn2.bias'],
            ['layer3.1.conv1.weight','layer3.1.bn1.weight', 'layer3.1.bn1.bias', 'layer3.1.conv2.weight','layer3.1.bn2.weight', 'layer3.1.bn2.bias'],
            ['layer2.0.conv1.weight','layer2.0.bn1.weight', 'layer2.0.bn1.bias', 'layer2.0.conv2.weight','layer2.0.bn2.weight', 'layer2.0.bn2.bias'],
            ['layer2.1.conv1.weight','layer2.1.bn1.weight', 'layer2.1.bn1.bias', 'layer2.1.conv2.weight','layer2.1.bn2.weight', 'layer2.1.bn2.bias'],
            ['conv1.weight'],
            ['bn1.weight', 'bn1.bias'],
            ['layer1.0.conv1.weight','layer1.0.bn1.weight', 'layer1.0.bn1.bias', 'layer1.0.conv2.weight','layer1.0.bn2.weight', 'layer1.0.bn2.bias'],
            ['layer1.1.conv1.weight','layer1.1.bn1.weight', 'layer1.1.bn1.bias', 'layer1.1.conv2.weight','layer1.1.bn2.weight', 'layer1.1.bn2.bias'],
            ['fc.weight', 'fc.bias'],
            ]

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, GroupNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

        for m in self.modules():
            if isinstance(m, Bottleneck):
                m.bn3.weight.data.fill_(0)
            if isinstance(m, BasicBlock):
                m.bn2.weight.data.fill_(0)

    def _make_layer(self, block, planes, blocks, stride=1, group_norm=0):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                norm2d(planes * block.expansion, group_norm),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample,
                            group_norm))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes, group_norm=group_norm))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x


def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model.
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
    return model

